package com.tea.controller;

import cn.hutool.json.JSONUtil;
import com.tea.common.core.controller.BaseController;
import com.tea.common.core.domain.AjaxResult;
import com.tea.common.utils.SecurityUtils;
import com.tea.common.utils.StringUtils;
import com.tea.funct.domain.TeaDetails;
import com.tea.funct.domain.TeaProduct;
import com.tea.funct.domain.TeaRenew;
import com.tea.funct.domain.res.CodePointInfo;
import com.tea.funct.domain.res.RewardQueryData;
import com.tea.funct.domain.res.RewardRecordData;
import com.tea.funct.domain.res.StatisticData;
import com.tea.funct.domain.vo.InUpDetailsVo;
import com.tea.funct.mapper.statistic.StatisticDataMapper;
import com.tea.funct.service.ITeaDetailsService;
import com.tea.funct.service.ITeaProductService;
import com.tea.funct.service.ITeaRenewService;
import com.tea.service.WxApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @PACKAGE_NAME: com.tea.controller
 * @CLASSNAME: WxAuthApiController
 * @DEACRIPTION: 小程序登录后接口控制器
 * @AUTHOR: GuoChen
 * @DATE: 2024/5/28
 * @WEEK: 周二
 **/
@Slf4j
@RestController
@RequestMapping("/authMarket")
public class WxAuthApiController extends BaseController {

    @Autowired
    private ITeaProductService teaProductService;
    @Autowired
    private ITeaDetailsService teaDetailsService;
    @Autowired
    private ITeaRenewService teaRenewService;
    @Autowired
    private StatisticDataMapper statisticDataMapper;
    @Autowired
    private WxApiService wxApiService;

    /**
     * 根据产品ID获取产品小程序推广码的绝对位置信息
     *
     * @param productId 产品ID
     * @return
     */
    @GetMapping("/getProductCodeConfig/{productId}")
    public AjaxResult getProductCodeConfig(@PathVariable("productId") Long productId) {
        log.info("根据产品ID获取产品小程序推广码的绝对位置信息: {}", productId);
        CodePointInfo codePointInfo = null;
        TeaProduct teaProduct = teaProductService.selectTeaProductById(productId);
        if (teaProduct != null && StringUtils.isNotBlank(teaProduct.getRemark())) {
            log.info("获取到通用的坐标配置信息为：{}", teaProduct.getRemark());
            try {
                codePointInfo = JSONUtil.toBean(teaProduct.getRemark(), CodePointInfo.class);
            } catch (Exception e) {
                log.error("根据产品ID获取产品小程序推广码的绝对位置信息异常：{}", e.getMessage());
                log.error(e.getMessage(), e);
                return AjaxResult.error();
            }
        }
        return AjaxResult.success(codePointInfo);
    }

    /**
     * 根据产品id查询该产品所有历史数据明细信息
     *
     * @param productId 产品id
     * @param day       天（7:7天; 30:30天; 90:90天; 365:1年; 1095:3年）
     * @return
     */
    @GetMapping("/getProductHisList/{productId}/{day}")
    public AjaxResult getProductHisList(@PathVariable("productId") Long productId,
                                        @PathVariable("day") Long day) {
        return wxApiService.getProductHisList(productId, day);
    }

    /**
     * 生成折线图
     *
     * @param productId 产品id
     * @param day       天（7:7天; 30:30天; 90:90天; 365:1年; 1095:3年）
     * @return
     */
    @GetMapping("/createProductHisEchart/{productId}/{day}")
    public AjaxResult createProductHisEchart(@PathVariable("productId") Long productId,
                                             @PathVariable("day") Long day) {
        return wxApiService.createProductHisEchart(productId, day);
    }

    /**
     * 获取会员充值项目信息
     *
     * @return
     */
    @GetMapping("/getRenewList")
    public AjaxResult getRenewList() {
        log.info("获取会员充值项目信息");
        List<TeaRenew> list = teaRenewService.selectTeaRenewList(null);
        return AjaxResult.success(list);
    }

    /**
     * 获取我的关注产品
     *
     * @return
     */
    @GetMapping("/getFocusProductList")
    public AjaxResult getFocusProductList() {
        log.info("获取我的关注产品");
        Long userId = SecurityUtils.getUserId();
        // Long userId = 1l;
        List<TeaProduct> list = teaProductService.selectProductByFocus(userId);
        return AjaxResult.success(list);
    }

    /**
     * 添加或移除我的关注
     *
     * @param productId 产品id
     * @return
     */
    @GetMapping("/addOrRemoveFacus/{productId}")
    public AjaxResult addOrRemoveFocus(@PathVariable("productId") Long productId) {
        return wxApiService.addOrRemoveFocus(productId);
    }

    /**
     * 批量移除我的关注
     *
     * @param productIds 产品id
     * @return
     */
    @PostMapping("/removeFacusList")
    public AjaxResult removeFacusList(@RequestBody List<Long> productIds) {
        return wxApiService.removeFacusList(productIds);
    }

    /**
     * 查询我的产品明细列表
     */
    @GetMapping("/getDetailList")
    public AjaxResult getDetailList() {
        log.info("查询我的产品明细列表");
        Long userId = SecurityUtils.getUserId();
        List<TeaDetails> list = teaDetailsService.selectTeaDetailsListByUserId(userId);
        return AjaxResult.success(list);
    }

    /**
     * 导入产品到产品明细处
     *
     * @param detailsVo 产品ids
     * @return
     */
    @PostMapping("/importDetails")
    public AjaxResult importDetails(@RequestBody InUpDetailsVo detailsVo) {
        return wxApiService.importDetails(detailsVo);
    }

    /**
     * 批量新增/修改产品明细
     */
    @PostMapping("/inUpDetails")
    public AjaxResult inUpDetails(@RequestBody InUpDetailsVo detailsVo) {
        return wxApiService.inUpDetails(detailsVo);
    }

    /**
     * 批量修改产品明细
     */
    @PutMapping("/updateDetails")
    public AjaxResult updateDetails(@RequestBody List<TeaDetails> teaDetails) {
        return wxApiService.updateDetails(teaDetails);
    }

    /**
     * 删除产品明细
     */
    @DeleteMapping("/deleteDetail/{id}")
    public AjaxResult deleteDetail(@PathVariable Long id) {
        log.info("删除产品明细: {}", id);
        return toAjax(teaDetailsService.deleteTeaDetailsById(id));
    }

    /**
     * 批量删除产品明细
     */
    @DeleteMapping("/deleteDetailAll")
    public AjaxResult deleteDetailAll(@RequestBody InUpDetailsVo detailsVo) {
        log.info("删除所有产品明细: {}", detailsVo);
        List<Long> detailIdList = detailsVo.getIds();
        long[] detailIds = detailIdList.stream().mapToLong(t -> t.longValue()).toArray();
        Long[] ids = new Long[detailIds.length];
        for (int i = 0; i < detailIds.length; i++) {
            ids[i] = detailIds[i];
        }
        int success = teaDetailsService.deleteTeaDetailsByIds(ids);
        if (success > 0) {
            log.info("批量移除成功！");
        } else {
            log.info("批量移除失败！");
        }
        return toAjax(success);
    }


    /**
     * 获取用户统计信息
     *
     * @return
     */
    @GetMapping("/getExtendData")
    public AjaxResult getExtendData() {
        /**
         * 1.查询累计奖励天数
         * 2.查询本月奖励天数
         * 3.查询累积会员用户
         * 4.查询累计客户
         * 5.查询已成交订单量
         * 6.查询推广海报
         */
        Long userId = SecurityUtils.getUserId();
        StatisticData data = new StatisticData();
        data = statisticDataMapper.getStatisticDataByUserId(userId);
        return AjaxResult.success(data);
    }

    /**
     * 获取用户奖励信息
     *
     * @return
     */
    @GetMapping("/getRewardData")
    public AjaxResult getRewardData() {
        /**
         * 7.查询可提取奖励天数
         * 8.查询已提取会员天数
         */
        Long userId = SecurityUtils.getUserId();
        RewardQueryData data = new RewardQueryData();
        data = statisticDataMapper.getRewardDataByUserId(userId);
        return AjaxResult.success(data);
    }

    /**
     * 提取会员天数到账
     *
     * @param day 提取天数
     * @return
     */
    @PutMapping("/withdrawAccount/{day}")
    public AjaxResult withdrawAccount(@PathVariable("day") Long day) {
        return wxApiService.withdrawAccount(day);
    }

    /**
     * 查询用户奖励历史信息
     *
     * @return
     */
    /**
     * 查询用户奖励/兑换历史信息
     *
     * @param rewardType 类型(0:奖励,1兑换)
     * @return
     */
    @GetMapping("/getRewardRecords/{rewardType}")
    public AjaxResult getRewardRecords(@PathVariable("rewardType") String rewardType) {
        Long userId = SecurityUtils.getUserId();
        List<RewardRecordData> list = new ArrayList<>();
        list = statisticDataMapper.getRewardRecordsByUserId(userId, rewardType);
        return AjaxResult.success(list);
    }

    // TODO
    // member需 新增推广码绝对路径/相对路径字段，新增推广小程序码绝对路径/相对路径字段

    /**
     * 看广告得限时体验接口
     *
     * @return
     */
    @GetMapping("/setLimitedExperience")
    public AjaxResult setLimitedExperience() {
        return wxApiService.setLimitedExperience();
    }

    /**
     * 查询邀请用户信息
     *
     * @return
     */
    @GetMapping("/getInvitationUserData")
    public AjaxResult getInvitationUserData() {
        return wxApiService.getInvitationUserData();
    }

}
